<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Event;

class OrderRefund extends Base
{
    protected $name = 'order_refund';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,account,code,nickname,mobile');
    }

    public function father()
    {
        return $this->hasOne(Order::class, 'id', 'order_id')->field('id,sn');
    }

    public function business()
    {
        return $this->hasOne(Business::class, 'id', 'business_id')
            ->field('id,title,logo,mobile,return_contacts,return_mobile,return_full_address');
    }

    public function express()
    {
        return $this->hasOne(Express::class, 'id', 'express_id')->field('id,title');
    }

    public function getProductAttr($value, $data)
    {
        return OrderProduct::whereIn('id', $data['op_ids'])
            ->field('id,title,num,sku_name,icon,vip_price')->select()->toArray();
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getExamineTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }


    public function getRefundTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    public function getProductStatusTextAttr($value, $data)
    {
        $arr = [0 => '-', 1 => '未收到货物', 2 => '已收到货'];
        return $arr[$data['product_status']];
    }

    public function getStatusTextAttr($value, $data)
    {
        $arr = [0 => '-', 1 => '等待商家同意', 2 => '等待寄回商品', 3 => '等待商家确认', 4 => '退款成功', 5 => '未通过申请'];
        return isset($arr[$data['status']]) ? $arr[$data['status']] : '';
    }

    public function getImagesAttr($value)
    {
        return $value ? explode(',', $value) : '';
    }

    public static function refundSave($param, $user): array
    {
        parent::startTrans();
        try {
            $order = Order::where(['id' => $param['order_id'], 'uid' => $user->id])->field('id,status,business_id,pay_way,order_type')->find();
            if (empty($order)) {
                return ['code' => -1, 'msg' => '订单错误'];
            }
            if (in_array($order->order_type, [1, 2, 5])) {
                return ['code' => -1, 'msg' => '该订单无法申请退款'];
            }

            if (!in_array($order->getData('status'), [1, 2, 3, 4, 6])) {
                return ['code' => -1, 'msg' => '该订单无法申请退款'];
            }

            $list = OrderProduct::where('order_id', $param['order_id'])
                ->where('return_status', 0)
                ->whereIn('id', $param['id'])
                ->withoutField('cate_1,profit,cost,spec_value_id')
                ->select();
            if ($list->isEmpty()) {
                return ['code' => -1, 'msg' => '退款商品错误'];
            }
            $currencyTotal = 0;
            $chainBeanTotal = 0;
            $loveBeanTotal = 0;
            $vipIntegTotal = 0;
            $redCoinTotal = 0;
            $discountTotal = 0;
            $total = 0;
            $discount_id = [];
            $ids = [];
            foreach ($list as $item) {
                $total += $item->vip_price * $item->num;
                $currencyTotal += $item->currency * $item->num;
                $chainBeanTotal += $item->chain_bean * $item->num;
                $loveBeanTotal += $item->love_bean * $item->num;
                $vipIntegTotal += $item->vip_integ * $item->num;
                $redCoinTotal += $item->red_coin * $item->num;
                $discountTotal += $item->deduct;
                if ($item->discount_id) {
                    $discount_id[] = $item->discount_id;
                }
                $ids[] = $item->id;
            }
            parent::create([
                'sn'             => 'TK' . date('YmdHis') . $user->id . rand(100000, 999999),
                'order_id'       => $param['order_id'],
                'uid'            => $user->id,
                'product_status' => isset($param['product_status']) ? $param['product_status'] : 0,
                'pay_way'        => $order->getData('pay_way'),
                'reason'         => $param['reason'],
                'type'           => $param['type'],
                'total'          => $total - $currencyTotal - $chainBeanTotal - $loveBeanTotal - $redCoinTotal - $vipIntegTotal - $discountTotal,
                'describe'       => $param['describe'],
                'images'         => isset($param['images']) ? $param['images'] : '',
                'currency'       => $currencyTotal,
                'chain_bean'     => $chainBeanTotal,
                'love_bean'      => $loveBeanTotal,
                'vip_integ'      => $vipIntegTotal,
                'red_coin'       => $redCoinTotal,
                'deduct'         => $discountTotal,
                'discount_id'    => $discount_id ? implode(',', $discount_id) : '',
                'business_id'    => $order->business_id,
                'op_ids'         => implode(',', $ids)
            ]);
            //检测订单中的商品是否全部申请退款退货
            $count = OrderProduct::where('order_id', $param['order_id'])->count();
            /*if ($count == count($list)) {
                $order->is_return = 2;
            } else {
                $order->is_return = 1;
            }*/
            $order->is_return = -1;
            $order->save();
            OrderProduct::update(['return_time' => time(), 'return_status' => 1], ['id' => $ids]);
            parent::commit();
            return ['code' => 1, 'msg' => '提交成功，请等待商家审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function businessEdit($param, $business): array
    {
        parent::startTrans();
        try {
            $info = parent::where(['id' => $param['id'], 'business_id' => $business->id, 'is_del' => 0])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单无效'];
            }
            $op_ids = explode(',', $info->op_ids);
            switch ($param['type']) {
                case "examine":
                    if ($info->getData('status') != 1) {
                        return ['code' => -1, 'msg' => '订单已经审核，请勿重复审核'];
                    }
                    if ($param['status'] == 2) {
                        if ($info['type'] == 1) {
                            if('wechat' == $info->getData('pay_way')){
                                /*if(!isset($param['method']) && !in_array($param['method'], ['JSAPI', 'APP'])){
                                    return ['code' => -1, 'msg' => '请选择微信退款方式'];
                                }*/
                                $param['method'] = 'JSAPI';
                                $info->refund_method = $param['method'];
                            }
                            $res = Event::trigger('OrderRefund', $info);
                            if($res[0]['code'] != 1){
                                return ['code' => -1, 'msg' => '退款失败~'];
                            }
                        } else {
                            $info->status = 2;
                            $info->examine_time = time();
                            $info->save();
                            OrderProduct::update(['return_status' => 2], ['id' => $op_ids]);
                        }

                        /*$user = User::where('id', $info->uid)->find();
                        $user->consume_total -= $info->total;
                        $user->consume_total < 0 && $user->consume_total = 0;
                        $user->save();*/
                    } else {
                        if (!isset($param['reject_msg']) || !$param['reject_msg']) {
                            return ['code' => -1, 'msg' => '请填写不同意理由'];
                        }
                        $info->status = 5;
                        $info->examine_time = time();
                        $info->reject_msg = $param['reject_msg'];
                        $info->save();
                        //商品回归初始状态
                        OrderProduct::update(
                            ['return_status' => 0, 'return_time' => 0],
                            ['id' => $op_ids]
                        );
                        $count = OrderProduct::where('order_id', $info->order_id)
                            ->where('return_status', '>', 0)->count();

                        Order::update(['id' => $info->order_id, 'is_return' => $count ? 1 : 0]);
                    }
                    break;
                case "receipt":
                    if ($info->getData('status') != 3) {
                        return ['code' => -1, 'msg' => '操作失败：订单状态错误'];
                    }
                    if ($param['status'] == 2) {
                        if('wechat' == $info->getData('pay_way')){
                            /*if(!isset($param['method']) && !in_array($param['method'], ['JSAPI', 'APP'])){
                                return ['code' => -1, 'msg' => '请选择微信退款方式'];
                            }*/
                            $param['method'] = 'JSAPI';
                            $info->refund_method = $param['method'];
                        }
                        Event::trigger('OrderRefund', $info);
                    } else {
                        $info->status = 2;
                        $info->save();
                    }
                    break;
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function userEdit($param, $user): array
    {
        parent::startTrans();
        try {
            $info = parent::where(['id' => $param['id'], 'uid' => $user->id, 'is_del' => 0])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单无效'];
            }

            switch ($param['type']) {
                case "express":
                    if ($info->status != 2) {
                        return ['code' => -1, 'msg' => '操作失败：该订单状态不允许上传物流信息'];
                    }
                    $info->express_id = $param['express_id'];
                    $info->express_title = $param['express_title'];
                    $info->express_code = $param['express_code'];
                    $info->receiver_tel = $param['receiver_tel'];
                    $info->status = 3;
                    $info->express_time = time();
                    $info->save();
                    OrderProduct::update(['return_status' => 3], ['id' => explode(',', $info->op_ids)]);
                    break;

            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
